<template>
  <div class="container">
    <a-card :bordered="false">
      <my-button type='add' @click="open"></my-button>
      <a-table :pagination="pagination" rowKey="id" :columns="columns" :dataSource="list" style="margin:15px 0" @change="handleTableChange">
        <template #action="action,row">
          <a-button ghost style="margin-right:5px" :type="row.status === 0 ? 'primary' : 'danger'" @click="changeStatus(row)">
            {{ row.status === 1 ? '禁用' : '恢复' }}
          </a-button>
          <a-button style="margin-right:5px" type="primary" ghost @click="toEdit(row)">修改</a-button>
          <a-button style="margin-right:5px" type="danger" @click="toRemove(row)">删除</a-button>
        </template>
      </a-table>
    </a-card>
    <!-- 弹窗 -->
    <a-modal :maskClosable="false" :destroyOnClose='true' title="操作" v-model="modal" @ok="submit" :width='600'>
      <a-form :form="form">
        <a-form-item label="角色名" v-bind="formItemLayout">
          <a-input placeholder="请输入角色名" v-decorator="['username',{rules: [{ required: true, message: '请输入角色名' }]}]"></a-input>
        </a-form-item>
        <a-form-item label="手机号" v-bind="formItemLayout">
          <a-input placeholder="请输入手机号" v-decorator="['phone',{rules: [{ required: true, message: '请输入手机号' }]}]"></a-input>
        </a-form-item>
        <a-form-item label="密码" v-bind="formItemLayout">
          <a-input placeholder="请输入密码" v-decorator="['password']"></a-input>
        </a-form-item>
        <a-form-item v-if="record.id" label="角色" v-bind="formItemLayout">
          <a-select mode='multiple' v-decorator="['roles',{rules: [{ required: true, message: '请选择角色' }]}]" placeholder="请选择角色">
            <a-select-option v-for="item in roleList" :key="item.id">
              {{item.name}}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="城市" v-bind="formItemLayout">
          <region-select :simple='true' v-decorator="['city_permission']" @change="handleChange"></region-select>
          <a-tag style="margin-right: 10px;" v-for="tag in cityList" :key="tag.code" closable @close="close(tag)">
            {{tag.city}}
          </a-tag>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import * as Api from '@/api/authManage'

export default {
  computed: {
    pagination() {
      const { page, per_page } = this.payload
      return {
        current: Number(page),
        pageSize: Number(per_page),
        total: this.total
      }
    }
  },
  data() {
    const { page = 1, per_page = 12 } = this.$route.query
    return {
      modal: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        }
      },
      columns: [
        { title: '用户名字', dataIndex: 'username' },
        { title: '手机号', dataIndex: 'phone' },
        { title: '最后登陆', dataIndex: 'last_time' },
        { title: '最后登陆ip', dataIndex: 'login_ip' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 250 },
      ],
      form: this.$form.createForm(this),
      list: [],
      record: {},
      roleList: [],
      cityList: [],
      payload: {
        page: Number(page),
        per_page: Number(per_page)
      },
      total: 0
    };
  },
  mounted() {
    this.fetchList()
  },
  methods: {
    async fetchList() {
      const { list, total } = await Api.memberList(this.payload)
      const data = await Api.roleList()
      this.roleList = data.list
      this.list = list
      this.total = total
    },
    open() {
      this.modal = true
      this.cityList = []
      this.record = {}
    },
    toEdit(row) {
      this.modal = true
      const d = { ...row }
      this.record = d
      console.log(d)
      let { username, phone, roles, city_permission } = d
      roles = roles.map(it => it.id)
      this.cityList = city_permission
      this.$nextTick(() => {
        this.form.setFieldsValue({
          username, phone, roles,
        })
      })
    },
    fetchData(payload = {}) {
      this.saveParams(payload)
    },
    handleTableChange(e) {
      this.payload.page = e.current
      this.fetchData(e)
    },
    toRemove({ id, username }) {
      this.$confirm({
        title: '删除',
        content: `您确定要删除${username}吗？`,
        onOk: async () => {
          await Api.memberRemove(id)
          this.fetchList()
        }
      })
    },
    // handleChange
    handleChange(value, name) {

      if (name) {
        let obj = {
          city: name.split(" ").pop(),
          code: value.pop()
        }
        let status = false
        this.cityList.map(it => {
          if (it.city === obj.city) {
            status = true
          }
        })
        !status && this.cityList.push(obj)
      }
    },
    close(tag) {
      let i = this.cityList.indexOf(tag)
      this.cityList.splice(i, 1)
    },
    // submit
    submit() {
      this.form.validateFields(async (err, data) => {
        if (!err) {
          let d = { ...data }
          const { id = '' } = this.record
          console.log(d)
          d.role_ids = d.roles && d.roles.join(",")
          d.city_permission = JSON.stringify(this.cityList)

          if (id) {
            d.id = id
            await Api.memberUpdate(d)
          } else {
            await Api.memberAdd(d)
          }
          this.modal = false
          this.fetchList()
        }
      })
    },
    async changeStatus(row) {
      await Api.memberChange(row)
      this.fetchList()
    },
  },
}
</script>

<style lang="scss" scoped>
</style>
